/*
 * Copyright 2010 Gal Dolber.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.unnison.demo.client.blippanel;

import com.google.inject.Inject;
import com.google.inject.Provider;

import com.unnison.demo.client.blippanel.BlipPanel.BlipPanelBinder;
import com.unnison.demo.client.common.HasInnerText;
import com.unnison.demo.client.common.HasViews;
import com.unnison.demo.client.main.MainPresenter;
import com.unnison.framework.client.GuitPresenter;
import com.unnison.framework.client.binder.GuitBinder;
import com.unnison.framework.client.binder.ViewField;
import com.unnison.framework.client.binder.ViewHandler;
import com.unnison.framework.client.place.Place;
import com.unnison.framework.client.place.PlaceName;

import java.util.ArrayList;

@PlaceName("blips")
public class BlipPanel extends GuitPresenter<BlipPanelBinder> implements Place<Void> {

    public static interface BlipPanelBinder extends GuitBinder<BlipPanel> {
    }

    @ViewField
    public HasViews panel;

    @ViewField
    public HasInnerText time;
    
    private final Provider<Blip> blipProvider;

    private final MainPresenter mainPresenter;

    private final ArrayList<Blip> blips = new ArrayList<Blip>();

    @Inject
    public BlipPanel(Provider<Blip> blipProvider, MainPresenter mainPresenter) {
        this.blipProvider = blipProvider;
        this.mainPresenter = mainPresenter;
    }

    @Override
    public void go(Void data) {
        mainPresenter.setContent(getView(), 7);
    }

    @ViewHandler
    protected void render$click() {
        destoyBlips();

        long ini = System.currentTimeMillis();

        for (int n = 0; n < 100; n++) {
            Blip blip = blipProvider.get();
            blips.add(blip);
            panel.add(blip.getView());
        }

        time.setInnerText(Long.toString(System.currentTimeMillis() - ini) + "ms");
    }

    private void destoyBlips() {
        panel.clear();
        for (Blip blip : blips) {
            blip.destroy();
        }
        blips.clear();
    }

    @ViewHandler
    protected void clear$click() {
        destoyBlips();
    }
}
